<script lang="ts" setup name="LoginForm4">
import LoginFormTitle from './LoginFormTitle.vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { useIcon } from '@/hooks/web/useIcon'
import { setTenantIdCache, getLoginFormCache, setLoginFormCache, removeLoginFormCache, setToken } from '@/utils/auth'
import { AuthApi } from '@/api/auth'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'

const { t } = useI18n()
const message = useMessage()
const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconLock = useIcon({ icon: 'ep:lock' })
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const { setLoginState, getLoginState } = useLoginState()
const { currentRoute, push } = useRouter()
const redirect = ref<string>('')
const loginLoading = ref(false)
const verifyRef = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字
const captchaMode = ref('dialog') // dialog 弹出式 | hover 触发式 | embedded 嵌入式

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

const LoginRules = {
  tenantName: [required],
  username: [required],
  password: [required]
}

const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  loginForm: {
    tenantName: import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || '',
    username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || '',
    password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || '',
    captchaVerification: '',
    rememberMe: true // 默认记录我。如果不需要，可手动修改
  }
})

// 获取验证码
const getCode = async () => {
  // 情况一，未开启：则直接登录
  if (loginData.captchaEnable === 'false') {
    await handleLogin()
  } else {
    // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录
    // 弹出验证码
    if (captchaMode.value === 'dialog') {
      verifyRef.value.open()
    } else {
      await handleLogin()
    }
  }
}

// 获取租户 ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    const res = await AuthApi.Tenant.getIdByName(loginData.loginForm.tenantName) // '租户ID'
    setTenantIdCache(res)
  }
}

// 记住我
const getLoginForm = () => {
  const loginForm = getLoginFormCache()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
      rememberMe: loginForm.rememberMe,
      tenantName: loginForm.tenantName ? loginForm.tenantName : loginData.loginForm.tenantName
    }
  }
}

// 根据域名，获得租户信息
const getTenantByWebsite = async () => {
  const website = location.host
  const res = await AuthApi.Tenant.getInfoByDomain(website) // {id: '租户ID', name: '租户名称'}
  if (res) {
    loginData.loginForm.tenantName = res.name
    setTenantIdCache(res.id)
  }
}

const verifySuccess = (data: any) => {
  loginData.loginForm.captchaVerification = data.captchaVerification
  if (captchaMode.value === 'dialog') {
    handleLogin()
  }
}

// 登录
const handleLogin = async () => {
  loginLoading.value = true
  try {
    await getTenantId()
    const data = await validForm()
    if (!data) {
      return
    }
    if (loginData.captchaEnable === 'true' && !loginData.loginForm.captchaVerification) {
      message.error(t('captcha', 'verification'))
      return
    }
    const res = await AuthApi.signIn(loginData.loginForm) // { code: 200 }
    if (!res) {
      return
    }
    if (loginData.loginForm.rememberMe) {
      setLoginFormCache(loginData.loginForm)
    } else {
      removeLoginFormCache()
    }
    setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }
    // 判断是否为SSO登录
    if (redirect.value.toLowerCase().indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      push({ path: redirect.value })
    }
  } finally {
    loginLoading.value = false
  }
}


watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

onMounted(() => {
  getLoginForm()
  getTenantByWebsite()
})
</script>

<template>
  <el-form v-show="getShow" ref="formLogin" :model="loginData.loginForm" :rules="LoginRules" class="login-form" label-position="top" label-width="120px" size="large">
    <el-row>
      <el-col :span="24">
        <el-form-item>
          <LoginFormTitle style="width: 100%" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item v-if="loginData.tenantEnable === 'true'" prop="tenantName">
          <el-input v-model="loginData.loginForm.tenantName" :placeholder="t('sign.fields.tenant', 'placeholder')" :prefix-icon="iconHouse" link type="primary" />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="username">
          <el-input v-model="loginData.loginForm.username" :placeholder="t('sign.fields.username', 'placeholder')" :prefix-icon="iconAvatar" />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="password">
          <el-input v-model="loginData.loginForm.password" :placeholder="t('sign.fields.password', 'placeholder')" :prefix-icon="iconLock" show-password type="password" @keyup.enter="getCode()" />
        </el-form-item>
      </el-col>
      <template v-if="loginData.captchaEnable === 'true'">
        <Verify v-if="captchaMode==='dialog'" ref="verifyRef" :captchaType="captchaType" :mode="captchaMode" size="large" @success="verifySuccess" />
        <el-form-item v-else class="flex w-full mt-[12px]">
          <div class="flex flex-1 justify-between m-[6px]">
            <Verify ref="verifyRef" :captchaType="captchaType" :mode="captchaMode" size="large" @success="verifySuccess" />
          </div>
        </el-form-item>
      </template>
      <el-col :span="24">
        <el-form-item>
          <el-row justify="space-between" class="items-center m-6px leading-[0]" style="width: 100%">
            <el-col :span="6" class="!flex justify-start">
              <el-checkbox v-model="loginData.loginForm.rememberMe">
                {{ t('sign', 'remember') }}
              </el-checkbox>
            </el-col>
            <el-col :offset="6" :span="12">
              <el-link style="float: right" type="primary" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">{{ t('sign.fields.password', 'forget') }}</el-link>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item>
          <CButton :loading="loginLoading" :title="t('sign.in', 'action')" class="w-[100%]" type="primary" @click="getCode()" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item>
          <el-row justify="space-between" class="items-center m-6px leading-[0]" style="width: 100%">
            <el-col :span="24" class="!flex justify-center">
              <el-link class="text-link" @click="setLoginState(LoginStateEnum.REGISTER)">{{ t('sign', 'noUser') }}</el-link>
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<style lang="scss" scoped>
.login-code {
  float: right;
  width: 100%;
  height: 38px;

  img {
    width: 100%;
    height: auto;
    max-width: 100px;
    vertical-align: middle;
    cursor: pointer;
  }
}
</style>
